package com.msb.mallcart.Service.impl;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.AuthConstant;
import com.msb.common.constant.CartConstant;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import com.msb.mallcart.Interceptor.AuthInterceptor;
import com.msb.mallcart.Service.ICartService;
import com.msb.mallcart.fegin.productFeignService;
import com.msb.mallcart.vo.Cart;
import com.msb.mallcart.vo.CartItem;
import com.msb.mallcart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther: xixifeng
 * @Date: 2022/11/10 - 11 - 10 - 17:55
 * @Description: com.msb.mallcart.Service.impl
 * @version: 1.0
 */
@Service
public class ICartServiceimpl implements ICartService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    productFeignService productFeignService;


    /**
     * 查询出当前登录用户的所有的购物车信息
     * @return
     */
    @Override
    public Cart getCartList() {

        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();

        Set<Object> keys = cartKeyOperation.keys();
        Cart cart = new Cart();
        List<CartItem> list=new ArrayList<>();

        for (Object k : keys) {
            String key = (String) k;
            Object o = cartKeyOperation.get(key);
            String json = (String) o;
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            list.add(cartItem);
        }
        cart.setItems(list);
        return cart;
    }



    /**
     * 把商品添加到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addCart(Long skuId, Integer num) {

        BoundHashOperations<String, Object, Object> hashOperations = getCartKeyOperation();
        // 如果Redis存储在商品的信息，那么我们只需要修改商品的数量就可以了
         Object o = hashOperations.get(skuId.toString());
        if (o != null) {
            // 说明已经存在了这个商品那么修改商品的数量即可
            String json=(String)o;
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            hashOperations.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }

         CartItem item= new CartItem();
        // 1.远程调用获取 商品信息
         R r = productFeignService.info(skuId);

        String skuInfo =(String) r.get("skuInfoJSON");
        SkuInfoVo skuInfoVo = JSON.parseObject(skuInfo, SkuInfoVo.class);
        item.setSkuId(skuInfoVo.getSkuId());
        item.setSpuId(skuInfoVo.getSpuId());
        item.setCount(num);
        item.setCheck(true);
        item.setImage(skuInfoVo.getSkuDefaultImg());
        item.setPrice(skuInfoVo.getPrice());
        item.setTitle(skuInfoVo.getSkuTitle());


        // 2.获取商品的销售属性
        List<String> skuSaleAttrs = productFeignService.getSkuSaleAttrs(skuId);
        item.setSkuAttr(skuSaleAttrs);
        // 3.把数据存储在Redis中
        hashOperations.put(skuId.toString(),JSON.toJSONString(item));

        return item;
    }


    /**  todo 对应关系                   key      value
     * ps:这里的redis是hash类型的<String, Object, Object>三部分
     *
     * 获取储存在redis中对应商品的String
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartKeyOperation() {
        // hash key: cart:skuId   skuId:cartItem
        //<String, Object, Object>  String :cart, Object :skuId, Object: cartItem
         MemberVO memberVO = AuthInterceptor.threadLocal.get();
        String key= CartConstant.CART_PERFIX+memberVO.getId();
        //String key= CartConstant.CART_PERFIX+"11";

         BoundHashOperations<String, Object, Object> BoundHashOperations
                 = stringRedisTemplate.boundHashOps(key);

         return BoundHashOperations;
    }


    //查询购物车中选中的商品信息
    @Override
    public List<CartItem> getUserCartItems() {

        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        List<Object> values = cartKeyOperation.values();
        List<CartItem> collect = values.stream().map((item) -> {
            String s = (String) item;
            CartItem cartItem = JSON.parseObject(s, CartItem.class);
            return cartItem;
        }).filter((item)->{

            return item.isCheck();
        }).collect(Collectors.toList());

        return collect;
    }
}
